// fileops.c

#include <stdio.h>
#include <string.h>
#include "fileops.h"

#define FILE_PATH "data.txt"
#define MAX_BOOKS 1000

void writeFile(Book book) {
    FILE *fp = fopen(FILE_PATH, "a");
    if (fp) {
        fprintf(fp, "%s,%s,%s,%s\n", book.title, book.author, book.ISBN, book.pub_date);
        fclose(fp);
    } else {
        printf("打开文件失败\n");
    }
}

void deleteFromFile(char ISBN[20]) {
    FILE *fp = fopen(FILE_PATH, "r");
    Book books[MAX_BOOKS];
    int count = 0;
    char line[256];

    if (fp) {
        while (fgets(line, sizeof(line), fp)) {
            sscanf(line, "%[^,],%[^,],%[^,],%[^\n]", books[count].title, books[count].author, books[count].ISBN, books[count].pub_date);
            count++;
        }
        fclose(fp);
    } else {
        printf("打开文件失败\n");
        return;
    }

    fp = fopen(FILE_PATH, "w");
    if (fp) {
        for (int i = 0; i < count; i++) {
            if (strcmp(books[i].ISBN, ISBN) != 0) {
                fprintf(fp, "%s,%s,%s,%s\n", books[i].title, books[i].author, books[i].ISBN, books[i].pub_date);
            }
        }
        fclose(fp);
    } else {
        printf("打开文件失败\n");
    }
}

void findInFile(char keyword[100]) {
    FILE *fp = fopen(FILE_PATH, "r");
    char line[256];

    if (fp) {
        while (fgets(line, sizeof(line), fp)) {
            if (strstr(line, keyword)) {
                printf("%s", line);
            }
        }
        fclose(fp);
    } else {
        printf("打开文件失败\n");
    }
}

void modifyInFile(char ISBN[20], Book book) {
    FILE *fp = fopen(FILE_PATH, "r");
    Book books[MAX_BOOKS];
    int count = 0;
    char line[256];

    if (fp) {
        while (fgets(line, sizeof(line), fp)) {
            sscanf(line, "%[^,],%[^,],%[^,],%[^\n]", books[count].title, books[count].author, books[count].ISBN, books[count].pub_date);
            count++;
        }
        fclose(fp);
    } else {
        printf("打开文件失败\n");
        return;
    }

    fp = fopen(FILE_PATH, "w");
    if (fp) {
        for (int i = 0; i < count; i++) {
            if (strcmp(books[i].ISBN, ISBN) == 0) {
                fprintf(fp, "%s,%s,%s,%s\n", book.title, book.author, book.ISBN, book.pub_date);
            } else {
                fprintf(fp, "%s,%s,%s,%s\n", books[i].title, books[i].author, books[i].ISBN, books[i].pub_date);
            }
        }
        fclose(fp);
    } else {
        printf("打开文件失败\n");
    }
}

void listFromFile(void) {
    FILE *fp = fopen(FILE_PATH, "r");
    char line[256];
    if (fp) {
        while (fgets(line, sizeof(line), fp)) {
            printf("%s", line);
        }
        fclose(fp);
    } else {
        printf("打开文件失败\n");
    }
}
